package com.spring.Transaction;


import com.spring.AOP.AopInterface.MethodInterceptor;
import com.spring.AOP.AopInterface.ProceedJoinPoint;
import com.spring.springAnnotation.Autowired;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

public class TransactionInterceptor implements MethodInterceptor {

    private static final TransactionManager transactionManager = new TransactionManager();
    @Override
    public Object invoke(ProceedJoinPoint joinPoint) throws InvocationTargetException, IllegalAccessException, SQLException {
        //获取方法上的注解
        Method method = joinPoint.getMethod();
        Transactional transactional = method.getAnnotation(Transactional.class);
        if (transactional == null) {
            return joinPoint.proceed();
        }
        transactionManager.begin();
        try {
            Object result = joinPoint.proceed();
            transactionManager.commit();
            return result;
        } catch (Exception e) {
            transactionManager.rollback();
            throw e;
        }

    }
}
